(async function confirm() {
    const resp = await API.profile();
    if (resp.code !== 0) {
        alert(resp.msg);
        location.href = './login.html'
        return
    } else {
        console.log(resp)
        const nickname = $('#nickname');
        const loginId = $('#loginId');
        nickname.innerText = resp.data.nickname;
        loginId.innerText = resp.data.loginId;

    }
})();

function createDom(type = 'robot', content, createdAt) {
    const container = $('.chat-container');
    const msgItem = $$$('div');
    msgItem.className = 'chat-item';

    if (type === 'me') {
        msgItem.classList.add('me');
        msgItem.innerHTML = `<img class="chat-avatar" src="./asset/avatar.png" />
        <div class="chat-content">${content}</div>
        <div class="chat-date">${formateDate(createdAt)}</div>`;
    } else {
        msgItem.innerHTML = `<img class="chat-avatar" src="./asset/robot-avatar.jpg" />
        <div class="chat-content">${content}</div>
        <div class="chat-date">${formateDate(createdAt)}</div>`
    }
    container.appendChild(msgItem);
    container.scrollTop = container.scrollHeight;
}

async function getInfo() {
    const conversation = await API.getHistory();
    console.log(conversation)
    conversation.data.forEach(item => {
        if (item.from === $('.aside-account').innerText) {
            createDom('me', item.content, item.createdAt);

        } else {
            createDom('robot', item.content, item.createdAt);
        }
    });
}

const exit = $('.close');
exit.onclick = () => {
    const date = confirm('确认退出吗？');
    if (date) {
        API.loginOut();
        location.href = './login.html'
    }
}


getInfo();

const form = $('.msg-container');
let disChat = false;

form.onsubmit = async function (e) {
    e.preventDefault();
    if (disChat) {
        return
    }
    const formData = new FormData(form);
    const txtMsgDom = $('#txtMsg');
    const txtMsg = formData.get('txtMsg');
    if (!txtMsg.trim()) {
        txtMsgDom.value = '';
        return
    }
    const createdAt = Date.now();
    createDom('me', txtMsg, createdAt);
    console.log(txtMsg);

    txtMsgDom.value = '';
    disChat = true;
    const resp = await API.sendChat(txtMsg);
    if (resp.code === 0) {
        console.log(resp.data)
        createDom('robot', resp.data.content, resp.data.createdAt);
        disChat = false;
    }
}